package com.jspx.weixin.action;

import com.jspx.boot.environment.Environment;
import com.jspx.boot.sign.OAuthOpenIdType;
import com.jspx.boot.sign.SexType;
import com.jspx.json.JSONObject;
import com.jspx.sioc.annotation.Ref;
import com.jspx.txweb.annotation.HttpMethod;
import com.jspx.txweb.env.TXWebIoc;
import com.jspx.txweb.online.OnlineManager;
import com.jspx.txweb.support.ActionSupport;
import com.jspx.txweb.table.OAuthOpenId;
import com.jspx.txweb.util.RequestUtil;
import com.jspx.utils.StringUtil;
import com.jspx.weixin.WeiXinManager;
import com.jspx.weixin.env.WeiXinEnv;
import com.jspx.weixin.table.WeiXinUser;
import com.jspx.weixin.util.WeiXinUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.weixin4j.Weixin;
import org.weixin4j.model.sns.SnsUser;

/**
 * Created by Administrator on 2017/8/8.
 * 联动到系统登陆信息
 */
@HttpMethod(caption = "微信授权接口")
public class WeiXinOAuth2Action extends ActionSupport {
    final static private Logger log = LoggerFactory.getLogger(WeiXinOAuth2Action.class);

    final static private String KEY_code= "code";
    final static private String KEY_state= "state";

    protected OnlineManager onlineManager;
    @Ref(name = TXWebIoc.onlineManager)
    public void setOnlineManager(OnlineManager onlineManager) {
        this.onlineManager = onlineManager;
    }

    @Override
    public String execute() throws Exception {
        String code = getString(KEY_code);
        if (StringUtil.isNULL(code)) return ERROR;

        String state = getString(KEY_state);
        String weiXinState = (String)session.getAttribute(WeiXinEnv.weiXinState);
        if (!weiXinState.startsWith(state))
        {
            //这里是微信提供的一种验证，防止跨域跳转攻击
            printError("state 验证失败",Environment.HTTP_status_400);
            return NONE;
        }

        Weixin weiXin = WeiXinManager.getWeinXin();
        String accessToken =  weiXin.getToken().getAccess_token();
         if (WeiXinEnv.snsapi_userinfo.equalsIgnoreCase((String)session.getAttribute(WeiXinEnv.weiXinScope)))
        {
            //这里能得到用户的 信息
            SnsUser snsUser =  weiXin.sns().getSnsUserByCode(code);
            if (snsUser!=null)
            {
                WeiXinUser weiXinUser = WeiXinUtil.toWeiXinUser(snsUser);
                session.setAttribute(WeiXinEnv.weiXinSnsUser,weiXinUser);
                session.setAttribute(WeiXinEnv.weiXinOpenId,weiXinUser.getOpenid());
                //-------------------------------------
                //如果用户不是游客，就绑定当前已经登陆的用户信息
                //绑定登陆微信
                OAuthOpenId newOAuthOpenId = new OAuthOpenId();
                newOAuthOpenId.setName(weiXinUser.getNickname());
                newOAuthOpenId.setSex(SexType.getSexZh(weiXinUser.getSex()));
                newOAuthOpenId.setOpenId(weiXinUser.getOpenid());
                newOAuthOpenId.setUnionid(weiXinUser.getUnionid());
                newOAuthOpenId.setFaceImage(weiXinUser.getHeadimgurl());
                newOAuthOpenId.setNamespace(OAuthOpenIdType.weiXin);
                newOAuthOpenId.setAccessToken(accessToken);
                JSONObject jsonobject = onlineManager.openIdLogin(newOAuthOpenId, RequestUtil.getRemoteAddr(request));
                if (jsonobject.getBoolean(Environment.SUCCESS))
                {
                    //微信账号绑定本地账号成功
                    return SUCCESS;
                } else {
                    printError(jsonobject.getString(Environment.message),  403);
                }
            }
        } else {
            //这里只能得到openid不能够得到用户信息
            String openId = weiXin.sns().getOpenId(code);
            session.setAttribute(WeiXinEnv.weiXinOpenId,openId);
            //绑定登陆微信
            OAuthOpenId newOAuthOpenId = new OAuthOpenId();
            newOAuthOpenId.setOpenId(openId);
            newOAuthOpenId.setNamespace(OAuthOpenIdType.weiXin);
            newOAuthOpenId.setAccessToken(accessToken);
            JSONObject jsonobject = onlineManager.openIdLogin(newOAuthOpenId, RequestUtil.getRemoteAddr(request));
            if (jsonobject.getBoolean(Environment.SUCCESS))
            {
                return SUCCESS;
            } else {
                printError(jsonobject.getString(Environment.message),  403);
            }
        }
        //跳转到界面
        return SUCCESS;
    }
}
